package com.whz.generic.utils;

import lombok.experimental.UtilityClass;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
import java.util.Optional;

/**
 * @author whz
 */
@UtilityClass
public class CommonWebUtils {

    public Optional<HttpServletResponse> getCurrentResponse() {
        return getRequestAttributes().map(ar -> ((ServletRequestAttributes) ar).getResponse());
    }

    public Optional<HttpServletRequest> getCurrentRequest() {
        return getRequestAttributes().map(ar -> ((ServletRequestAttributes) ar).getRequest());
    }

    /**
     * locale from header or server default
     *
     * @return request locale or default one
     */
    public Locale getCurrentLocaleOrDefault() {
        return getCurrentRequest().map(ServletRequest::getLocale).orElseGet(Locale::getDefault);
    }

    private static Optional<RequestAttributes> getRequestAttributes() {
        return Optional.of(RequestContextHolder.currentRequestAttributes())
                       .filter(ar -> ar instanceof ServletRequestAttributes);
    }
}